import os
from werkzeug.utils import secure_filename

# 获取当前文件所在目录的绝对路径
current_dir = os.path.dirname(__file__)

# 构建相对于项目根目录的上传文件夹路径
UPLOAD_FOLDER = os.path.join(current_dir, 'static', 'uploads')
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def upload_image(file, upload_folder):
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        print(f"处理文件: {filename}")  # 调试信息
        file_path = os.path.join(upload_folder, filename)
        # 检查是否同名已存在
        base, ext = os.path.splitext(filename)
        counter = 1
        new_filename = filename  # 初始设定为原始文件名
        while os.path.exists(file_path):
            # 只删除与当前上传文件同名的文件
            if filename != new_filename:
                os.remove(file_path)
                print(f"删除已存在的文件: {file_path}")  # 调试信息
            # 生成新的文件名
            new_filename = f"{base} ({counter}){ext}"
            file_path = os.path.join(upload_folder, new_filename)
            counter += 1
        try:
            file.save(file_path)
            print(f"成功保存文件: {new_filename}")  # 调试信息
            return new_filename  # 返回上传后的文件名
        except Exception as e:
            print(f"保存文件失败: {e}")  # 错误信息
            return None
    else:
        print("文件类型不允许")  # 调试信息
        return None

def delete_file(upload_folder, filename):
    file_path = os.path.join(upload_folder, filename)
    if os.path.exists(file_path):
        os.remove(file_path)
        print('成功删除')
